<template>
  <div>
    <ul class="list">
      <li
        class="item"
        v-for="item in letter"
        :key="item"
        :ref="item"
        @click="getInner"
        @touchstart="handletouchstart"
        @touchmove="handletouchmove"
        @touchend="handletouchend"
      >{{item}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "cityAlpha",
  props: {
    cities: Object
  },
  data() {
    return {
      flag: false,
      //   优化代码，在updated中获取A距离顶部的值
      startY: 0,
      //   优化代码，让滑动字母列表频率减少，通过一次性定时器增加页面性能
      timer: null
    };
  },
  updated() {
    // 获取A距离顶部的距离，先通过ref获取到dom元素
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    getInner(e) {
      this.$emit("change", e.target.innerText);
    },
    handletouchstart() {
      this.flag = true;
    },
    handletouchmove(e) {
      if (this.flag) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 88.4;
          // 获取移动位置距离A的位置有多少个字高。取得第几个字母,取得索引，A为0，b为1
          const index = Math.floor((touchY - this.startY) / 20);
          // 滑动到哪个字母，把字母传递给better-scroll的el
          if (index >= 0 && index < this.letter.length)
            this.$emit("change", this.letter[index]);
          // console.log(index)
          // console.log(this.$refs['A'])
        }, 16);
      }
    },
    handletouchend() {
      this.flag = false;
    }
  },
  computed: {
    letter() {
      const letters = [];
      for (let i in this.cities) {
        letters.push(i);
      }
      return letters;
    }
  }
};
</script>

<style lang="less" scoped>
.list {
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: center;
  right: 0;
  top: 1.7rem;
  bottom: 0;
  width: 0.4rem;
  color: #00bcd4;
  text-align: center;
  .item {
    line-height: 0.4rem;
  }
}
</style>
